<template>
  <div class="main">
    <div class="main-center">
      <el-alert
        title="充值提示"
        type="warning"
        description="More text description"
        show-icon
      >
        充值余额将不可以退款，请知悉。
      </el-alert>
      <el-form
        ref="formRef"
        :rules="rules"
        :model="form"
        class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
      >
        <el-form-item label="充值类型"> TRC </el-form-item>
        <el-form-item label="USDT汇率"> {{ USDTExchangeRate }} </el-form-item>
        <el-form-item label="充值数量" prop="amount">
          <el-input-number v-model="form.amount" :min="10" />
          <span class="ml-2">USDT</span>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="createLoading"
            @click="createPayment"
          >
            创建支付
          </el-button>
        </el-form-item>
      </el-form>
      <template v-if="createInfo.orderNo">
        <div class="flex items-center gap-4">
          <span>收款地址：{{ createInfo.toAddress }}</span>
          <el-button
            v-if="isSupported"
            type="success"
            plain
            size="small"
            @click="copy(createInfo.toAddress)"
          >
            {{ copied ? "已复制" : "复制" }}
            <el-icon class="el-icon--right">
              <DocumentChecked v-if="copied" />
              <CopyDocument v-else />
            </el-icon>
          </el-button>
        </div>
        <div>订单编号：{{ createInfo.orderNo }}</div>
        <div>待付金额：{{ createInfo.actualAmount }} USDT</div>
        <el-alert type="error">
          需按待付金额全额支付，注意尾号支付，否则无法到账。
        </el-alert>
      </template>
      <template v-if="showInfo.orderNo">
        <div>积分：{{ showInfo.points }}</div>
        <div>订单状态：{{ showInfo.status }}</div>
      </template>
      <template v-if="qr">
        <div>
          <el-button type="success" text @click="getPaymentQrcode">
            刷新二维码
          </el-button>
        </div>
        <el-image :src="qr" alt="" />
      </template>
    </div>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";
import { CopyDocument, DocumentChecked } from "@element-plus/icons-vue";
import {
  paymentCreate,
  paymentStatus,
  paymentAddressQrcode
} from "@/api/userPayApi";
import { getUsdtCnyExchangeRate } from "@/api/globalConfigApi";
import { useClipboard } from "@vueuse/core";
import { ref, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
const userStore = useUserStoreHook();

const qr = ref("");
const formRef = ref<FormInstance>();
const form = ref({
  amount: 0
});
// const USDT汇率
const USDTExchangeRate = ref(0);
const rules: FormRules = {
  amount: [
    {
      type: "number",
      required: true,
      message: "请输入正确的数字",
      trigger: "blur"
    },
    {
      pattern: /^[-+]?(\d+(\.\d+)?|\.\d+)$/,
      message: "请输入正确的数字",
      trigger: "blur"
    }
  ]
};
const createInfo = ref({
  orderNo: "",
  actualAmount: 0,
  toAddress: ""
});
const { copy, copied, isSupported } = useClipboard({
  source: createInfo.value.toAddress
});
const createLoading = ref(false);
const createPayment = async () => {
  await formRef.value?.validate(async valid => {
    if (valid) {
      try {
        if (form.value.amount < 10) {
          ElMessage.warning("最低支付金额为10USDT");
          return;
        }
        createLoading.value = true;
        const { data } = await paymentCreate(form.value.amount);
        createInfo.value = data;
        getPaymentQrcode();
        satusTimer();
      } finally {
        createLoading.value = false;
      }
    }
  });
};
const timer = ref();
const showInfo = ref({
  orderNo: "",
  status: "待支付",
  actualAmount: 0,
  points: 0
});
const getPaymentStatus = async (No: string) => {
  try {
    const { data } = await paymentStatus({ orderNo: No });
    const { status } = data;
    showInfo.value = data;
    if (status !== "待支付") {
      if (timer.value) clearInterval(timer.value);
      createInfo.value = {
        orderNo: "",
        actualAmount: 0,
        toAddress: ""
      };
      qr.value = "";
      userStore.getUserInfo();
    }
    if (status === "已支付") {
      ElMessage.success("支付成功");
    }
    if (status === "失败") {
      ElMessage.success("支付失败，请复制订单编号联系管理员");
    }
  } catch (error) {
    console.log(error);
  }
};
const satusTimer = () => {
  getPaymentStatus(createInfo.value.orderNo);
  if (timer.value) clearInterval(timer.value);
  timer.value = setInterval(() => {
    getPaymentStatus(createInfo.value.orderNo);
  }, 5000);
};
const getPaymentQrcode = async () => {
  try {
    const { data } = await paymentAddressQrcode(createInfo.value.orderNo);
    const url = URL.createObjectURL(data);
    qr.value = url;
  } catch (error) {
    console.log(error);
  }
};
onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value);
});
getUsdtCnyExchangeRate().then(res => {
  USDTExchangeRate.value = res?.data?.usdCny || 0;
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: center;
  .main-center {
    width: 500px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    .el-image {
      width: 300px;
    }
  }
}
</style>
